package com.jilefojing.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.jilefojing.beans.data.enums.ResponseEnum;
import com.jilefojing.beans.data.manager.response.EVideoData;
import com.jilefojing.beans.data.response.base.ResponseData;
import com.jilefojing.beans.enums.ProgressStatusForSource;
import com.jilefojing.beans.enums.StatusEnumForPublish;
import com.jilefojing.beans.exception.UserContextException;
import com.jilefojing.beans.pojos.EVideo;
import com.jilefojing.beans.pojos.enhanced.EnhancedEVideo;
import com.jilefojing.beans.query.EVideoQuery;
import com.jilefojing.beans.vo.Order;
import com.jilefojing.beans.vo.Pagination;
import com.jilefojing.beans.vo.UploadFile;
import com.jilefojing.context.beans.vo.UserContext;
import com.jilefojing.controller.base.BaseController;
import com.jilefojing.controller.convent.CommonConvent;
import com.jilefojing.qiniu.beans.enums.BucketEnum;
import com.jilefojing.service.IEVideoService;
import com.jilefojing.service.IRecommendService;
import com.jilefojing.util.Detect;
import com.jilefojing.util.QiniuUtil;

@Controller
@RequestMapping("video")
public class VideoController extends BaseController {
	@Autowired
	private IEVideoService eVideoService;
	@Autowired
	private IRecommendService recommendService;

	@RequestMapping("children-config.html")
	public String toChildrenConfig(HttpServletRequest request) throws UserContextException {
		UserContext userContext = super.getUserContext();

		return "video/children_config";
	}

	/**
	 * 更新父类与子类的关联关系
	 * 
	 * @param childId
	 * @param parentId
	 * @param optype
	 *            true增加关系 false删除关系
	 * @param request
	 * @return
	 * @throws UserContextException
	 */
	@RequestMapping(value = "relation-update", method = RequestMethod.POST)
	public @ResponseBody ResponseData relationUpdate(long childId, long parentId, boolean optype, HttpServletRequest request) throws UserContextException {
		UserContext userContext = super.getUserContext();

		ResponseData responseData = new ResponseData();
		try {
			EVideo eVideo = eVideoService.updateRelation(childId, parentId, optype, userContext);
			// responseData.setData(eVideo);
		} catch (UserContextException e) {
			if (e.getResponse() != null) {
				responseData.setResponseEnum(e.getResponse());
			} else {
				responseData.setResponseEnum(ResponseEnum.UNKNOWN);
				responseData.setResponseMessage(e.getMessage());
			}
		}

		return responseData;
	}

	@RequestMapping(value = "updateCover", method = RequestMethod.POST)
	public @ResponseBody ResponseData updateCover(long eVideoId, HttpServletRequest request) throws UserContextException, IOException {
		UserContext userContext = super.getUserContext();

		MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;

		MultipartFile coverFile = mulRequest.getFile("coverFile");

		UploadFile coverUploadFile = new UploadFile();
		coverUploadFile.setBytes(coverFile.getBytes());
		coverUploadFile.setSuffix(coverFile.getOriginalFilename().substring(coverFile.getOriginalFilename().lastIndexOf(".") + 1));

		ResponseData responseData = new ResponseData();
		try {
			EVideo eVideo = eVideoService.updateCover(eVideoId, coverUploadFile, userContext);
			responseData.setData(((EnhancedEVideo) eVideoService.getEnhanced(eVideo.getId(), userContext)).getCoverUrl());
		} catch (UserContextException e) {
			if (e.getResponse() != null) {
				responseData.setResponseEnum(e.getResponse());
			} else {
				responseData.setResponseEnum(ResponseEnum.UNKNOWN);
				responseData.setResponseMessage(e.getMessage());
			}
		}

		return responseData;
	}

	@RequestMapping(value = "update", method = RequestMethod.POST)
	public @ResponseBody ResponseData update(EVideo eVideo, HttpServletRequest request) throws UserContextException {
		UserContext userContext = super.getUserContext();

		ResponseData responseData = new ResponseData();
		try {
			eVideo = eVideoService.update(eVideo, userContext);
		} catch (UserContextException e) {
			if (e.getResponse() != null) {
				responseData.setResponseEnum(e.getResponse());
			} else {
				responseData.setResponseEnum(ResponseEnum.UNKNOWN);
				responseData.setResponseMessage(e.getMessage());
			}
		}

		return responseData;
	}

	@RequestMapping(value = "add", method = RequestMethod.POST)
	public @ResponseBody ResponseData add(EVideo eVideo, HttpServletRequest request) {
		ResponseData responseData = new ResponseData();

		try {
			UserContext userContext = super.getUserContext();

			eVideo = eVideoService.add(eVideo, userContext);
			responseData.setData(eVideo);
		} catch (UserContextException e) {
			if (e.getResponse() != null) {
				responseData.setResponseEnum(e.getResponse());
			} else {
				responseData.setResponseEnum(ResponseEnum.UNKNOWN);
				responseData.setResponseMessage(e.getMessage());
			}
		}

		return responseData;
	}

	@RequestMapping("add/page.html")
	public String addPage(HttpServletRequest request) throws UserContextException {
		Boolean isEntity = null;
		String isEntityStr = request.getParameter("isEntity");
		if (Detect.notEmpty(isEntityStr)) {
			isEntity = Boolean.valueOf(isEntityStr);
		}

		request.setAttribute("imgBucketToken", QiniuUtil.getToken(BucketEnum.IMG));
		request.setAttribute("imgBucketDomain", QiniuUtil.getDomainByBucket(BucketEnum.IMG));

		if (isEntity == null || isEntity) {
			request.setAttribute("videoBucketToken", QiniuUtil.getToken(BucketEnum.VIDEO));
			request.setAttribute("videoBucketDomain", QiniuUtil.getDomainByBucket(BucketEnum.VIDEO));
			return "video/video_add";
		}

		return "video/video_not_entity_add";
	}

	@RequestMapping("info.html")
	public String getInfo(HttpServletRequest request) throws UserContextException {
		// UserContext userContext =
		request.setAttribute("video", CommonConvent.convent2EVideoData((EnhancedEVideo) eVideoService.getEnhanced(Long.valueOf(request.getParameter("id")), null)));

		return "video/video_info";
	}

	@RequestMapping("list.html")
	public String toListPage(HttpServletRequest request) throws UserContextException {

		Boolean isEntity = null;
		String isEntityStr = request.getParameter("isEntity");
		if (Detect.notEmpty(isEntityStr)) {
			isEntity = Boolean.valueOf(isEntityStr);
		}

		if (isEntity == null || isEntity) {
			return "video/video_list";
		}
		return "video/video_not_entity_list";
	}

	@RequestMapping("list")
	public @ResponseBody Map<String, Object> getList(Boolean isEntity, Long parentId, String like_title, Short status, Short progressStatus, HttpServletRequest request) throws UserContextException {
		UserContext userContext = super.getUserContext();

		int page = Integer.valueOf(request.getParameter("page"));
		int rows = Integer.valueOf(request.getParameter("rows"));

		String sortsStr = request.getParameter("sort");
		String ordersStr = request.getParameter("order");

		Pagination<EnhancedEVideo> pagination = new Pagination<EnhancedEVideo>(page, rows, true);
		if (!Detect.notEmpty(sortsStr)) {
			pagination.addOrder(new Order(EVideo.COLUMN_SORT, Order.ORDER_DESC)).addOrder(new Order(EVideo.COLUMN_UPDATE_TIME, Order.ORDER_DESC));
		} else {
			super.addSorts(sortsStr, ordersStr, EVideo.FIELD_SORT, EVideo.COLUMN_SORT, pagination);
			super.addSorts(sortsStr, ordersStr, EVideo.FIELD_UPDATETIME, EVideo.COLUMN_UPDATE_TIME, pagination);
		}

		EVideoQuery eVideoQuery = new EVideoQuery();
		if (Detect.notEmpty(like_title)) {
			eVideoQuery.setLike_title(like_title);
		}
		eVideoQuery.setEntity(isEntity);
		if (parentId != null && parentId > 0) {
			eVideoQuery.setParentIds(Arrays.asList(new Long[] { parentId }));
		}
		if (status != null && status > 0) {
			eVideoQuery.setStatuses(Arrays.asList(new StatusEnumForPublish[] { StatusEnumForPublish.getStatusEnumByCode(status) }));
		}
		if (progressStatus != null && progressStatus > 0) {
			eVideoQuery.setProgressStatuses(Arrays.asList(new ProgressStatusForSource[] { ProgressStatusForSource.getProgressStatusEnumByCode(progressStatus) }));
		}

		pagination = eVideoService.getPagination(eVideoQuery, pagination, null);
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("total", pagination.getCount());
		List<EVideoData> videoDatas = new ArrayList<EVideoData>();
		if (Detect.notEmpty(pagination.getItems())) {
			pagination.setItems(eVideoService.appendEnhancedParent(pagination.getItems(), userContext));
			pagination.setItems(eVideoService.appendEnhancedChildren(pagination.getItems(), userContext));

			videoDatas = CommonConvent.convent2EVideoDatas(pagination.getItems());
			for (EVideoData _VideoData : videoDatas) {
				if (Detect.notEmpty(_VideoData.getChildren())) {
					for (EVideoData _child : _VideoData.getChildren()) {
						_child.setCoverUrl(null);
					}
				}
			}
		}
		result.put("rows", videoDatas);

		return result;
	}
}
